<?php

namespace app\common\service;

use app\common\model\User;
use EasyWeChat\Factory;
use think\Db;
use think\Env;

class Wechat
{
    /**
     * @var \EasyWeChat\MiniProgram\Application
     */
    protected $app;

    private $config;


    public function __construct()
    {
        $this->config = [
            'app_id' => config('site.appid'),
            'secret' => config('site.appsecret'),
        ];

        $this->app = Factory::miniProgram($this->config);
    }

    public function login($code)
    {
        return $this->app->auth->session($code);
    }

    public function getMobile($session, $iv, $encryptedData)
    {
        try {
            $decryptedData = $this->app->encryptor->decryptData($session, $iv, $encryptedData);
        } catch (\Throwable $th) {
            return '';
        }
        return isset($decryptedData['phoneNumber']) ? $decryptedData['phoneNumber'] : '';
    }

    public function qrcode($scene, $page)
    {
        $response = $this->app->app_code->getUnlimit($scene, [
            'page' => $page,
//            'env_version' => 'develop',
            'check_path' => false,
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->saveAs(ROOT_PATH . '/public/code', str_replace('/', '_', $page.'_'.$scene) . '.png');
            $path = '/code/' . $filename;
        } else {
            $path = "";
        }
        return $path;
    }

    public function qrWxcode($page = "pages/index/index")
    {
        if (file_exists(ROOT_PATH . '/public/code/' . config('site.appid') . '.png')) {
            return '/code/' . config('site.appid') . '.png';
        }
        $response = $this->app->app_code->get($page, [
            'width' => 240
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->saveAs(ROOT_PATH . '/public/code', config('site.appid') . '.png');
            $path = '/code/' . $filename;
        } else {
            $path = "";
        }
        return $path;
    }

    public function loginByCode(string $code)
    {
        $result = $this->app->auth->session($code);

        if (isset($result['errcode'])) {
            exception($result['errmsg']);
        }

        $openid = $result['openid'];

        $user = User::get(['openid' => $openid]);

        if (!$user) {
            $ip = request()->ip();
            $time = time();
            Db::startTrans();
            try {
                $user = User::create([
                    'level' => 1,
                    'score' => 0,
                    'jointime' => $time,
                    'joinip' => $ip,
                    'logintime' => $time,
                    'loginip' => $ip,
                    'prevtime' => $time,
                    'openid' => $openid,
                    'status' => 'normal'
                ], true);

                Db::commit();
            } catch (\Throwable $throwable) {
                Db::rollback();
            }
        }
        return $user;
    }
}